package absolute_zero.com.urbox;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Contacts;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class ContactChooser extends Activity 
{
	private ListView resultList;
	private EditText searchTerm;
	//private ArrayList<String> results;
	private boolean isPhoneNumber = true;
	private Filter dataFilter;
	//private String selectedContact = "";
	private ArrayList<Contact> contacts;
	private Map<String, Contact> IDtoContact;
	private ContactAdapter adapter;
	private String filepath;
	
	boolean has_file;
	
	/** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) 
  {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.contact_chooser);
      
      //fetch the filepath
      
      
      Bundle UserInfo = getIntent().getExtras();
      	if(UserInfo.containsKey("Filepath")){
      		filepath = (String)UserInfo.get("Filepath");
      		has_file = true;
      	}else{
      		has_file = false;
      	}
		
		 
      
      filepath = "";
      contacts = new ArrayList<Contact>();
      
      Cursor phoneCursor = getContentResolver().query(Contacts.Phones.CONTENT_URI, null, null, null, null); //for whatever reason, i can't get all the data from one cursor
      startManagingCursor(phoneCursor);
      
      Cursor dataCursor = getContentResolver().query(Contacts.ContactMethods.CONTENT_URI, null, null, null, null); 
      startManagingCursor(dataCursor); 
      
      Cursor photoCursor = getContentResolver().query(Contacts.Photos.CONTENT_URI, null, null, null, null);
      startManagingCursor(photoCursor);
      
      int phoneIndex = phoneCursor.getColumnIndex(Contacts.PhonesColumns.NUMBER);
      int phoneTypeIndex = phoneCursor.getColumnIndex(Contacts.PhonesColumns.TYPE);
      int personID = phoneCursor.getColumnIndex(Contacts.Phones.PERSON_ID);
      int phoneName = phoneCursor.getColumnIndex(Contacts.Phones.NAME);
      
      int dataIndex = dataCursor.getColumnIndex(Contacts.ContactMethods.DATA);
      int dataKind = dataCursor.getColumnIndex(Contacts.ContactMethods.KIND);
      int dataPersonID = dataCursor.getColumnIndex(Contacts.ContactMethods.PERSON_ID);
      int dataName = dataCursor.getColumnIndex(Contacts.ContactMethods.NAME);
      int dataType = dataCursor.getColumnIndex(Contacts.ContactMethods.TYPE);
      int imType = dataCursor.getColumnIndex(Contacts.ContactMethods.AUX_DATA);
      
      int photoIndex = photoCursor.getColumnIndex(Contacts.PhotosColumns.DATA);
      int photoPersonID = photoCursor.getColumnIndex(Contacts.PhotosColumns.PERSON_ID);
      
      IDtoContact = new TreeMap<String, Contact>();

      if (phoneCursor.getCount() > 0)
      {
	      phoneCursor.moveToFirst();
	      do
	      {
	    	  String ID = phoneCursor.getString(personID);
	    	  String phoneType = "";
	    	  int phoneTypeID = Integer.parseInt(phoneCursor.getString(phoneTypeIndex));
	    	  if (phoneTypeID == Contacts.PhonesColumns.TYPE_CUSTOM)
	    		  phoneType = "Phone Custom";
	    	  else if (phoneTypeID == Contacts.PhonesColumns.TYPE_FAX_HOME)
	    		  phoneType = "Phone FaxHome";
	    	  else if (phoneTypeID == Contacts.PhonesColumns.TYPE_FAX_WORK)
	    		  phoneType = "Phone FaxWork";
	    	  else if (phoneTypeID == Contacts.PhonesColumns.TYPE_HOME)
	    		  phoneType = "Phone Home";
	    	  else if (phoneTypeID == Contacts.PhonesColumns.TYPE_MOBILE)
	    		  phoneType = "Phone Mobile";
	    	  else if (phoneTypeID == Contacts.PhonesColumns.TYPE_OTHER)
	    		  phoneType = "Phone Other";
	    	  else if (phoneTypeID == Contacts.PhonesColumns.TYPE_PAGER)
	    		  phoneType = "Phone Pager";
	    	  else if (phoneTypeID == Contacts.PhonesColumns.TYPE_WORK)
	    		  phoneType = "Phone Work";
	    	  if (IDtoContact.containsKey(ID))
	    		  IDtoContact.get(ID).addNumber(phoneType + ":" + phoneCursor.getString(phoneIndex));
	    	  else
	    		  IDtoContact.put(ID, new Contact(ID, phoneCursor.getString(phoneName), phoneType + ":" + phoneCursor.getString(phoneIndex), null, null));
	      }
	      while (phoneCursor.moveToNext());
      }
      phoneCursor.close();
      
      if (dataCursor.getCount() > 0)
      {
    	  dataCursor.moveToFirst();
	      do
	      {
	    	  String ID = dataCursor.getString(dataPersonID);
	    	  String dataTypeString = "";
	    	  int dataTypeID = Integer.parseInt(dataCursor.getString(dataType));
	    	  if (dataCursor.getString(dataKind).equals(Integer.toString(Contacts.KIND_EMAIL))) //if it is an email address in the data field
	    	  {
	    		  if (dataTypeID == Contacts.ContactMethods.TYPE_CUSTOM)
	    			  dataTypeString = "Email Custom";
	    		  else if (dataTypeID == Contacts.ContactMethods.TYPE_HOME)
	    			  dataTypeString = "Email Home";
	    		  else if (dataTypeID == Contacts.ContactMethods.TYPE_OTHER)
	    			  dataTypeString = "Email Other";
	    		  else if (dataTypeID == Contacts.ContactMethods.TYPE_WORK)
	    			  dataTypeString = "Email Work";
	    		  if (IDtoContact.containsKey(ID))
	    			  IDtoContact.get(ID).addData(dataTypeString + ":" + dataCursor.getString(dataIndex));
	    		  else
	    			  IDtoContact.put(ID, new Contact(ID, dataCursor.getString(dataName), null, dataTypeString + ":" + dataCursor.getString(dataIndex), null));
	    	  }
	    	  else if (dataCursor.getString(dataKind).equals(Integer.toString(Contacts.KIND_IM)))
	    	  {
	    		  dataTypeID = Integer.parseInt(dataCursor.getString(imType).substring(dataCursor.getString(imType).indexOf(":") + 1));
	    		  Log.d("IM Type", dataCursor.getString(imType));
	    		  if (dataTypeID == Contacts.ContactMethods.PROTOCOL_AIM)
	    			  dataTypeString = "IM AIM";
	    		  else if (dataTypeID == Contacts.ContactMethods.PROTOCOL_GOOGLE_TALK)
	    			  dataTypeString = "IM GoogleTalk";
	    		  else if (dataTypeID == Contacts.ContactMethods.PROTOCOL_ICQ)
	    			  dataTypeString = "IM ICQ";
	    		  else if (dataTypeID == Contacts.ContactMethods.PROTOCOL_JABBER)
	    			  dataTypeString = "IM Jabber";
	    		  else if (dataTypeID == Contacts.ContactMethods.PROTOCOL_MSN)
	    			  dataTypeString = "IM MSN";
	    		  else if (dataTypeID == Contacts.ContactMethods.PROTOCOL_QQ)
	    			  dataTypeString = "IM QQ";
	    		  else if (dataTypeID == Contacts.ContactMethods.PROTOCOL_SKYPE)
	    			  dataTypeString = "IM Skype";
	    		  else if (dataTypeID == Contacts.ContactMethods.PROTOCOL_YAHOO)
	    			  dataTypeString = "IM Yahoo";

	    		  if (IDtoContact.containsKey(ID))
	    			  IDtoContact.get(ID).addExtra(dataTypeString + ":" + dataCursor.getString(dataIndex));
	    		  else
	    		  {
	    			  Contact temp = new Contact(ID, dataCursor.getString(dataName), null, dataCursor.getString(dataIndex), null);
	    			  temp.addExtra(dataTypeString + ":" + dataCursor.getString(dataIndex));
	    			  IDtoContact.put(ID, temp);
	    		  }
	    	  }
	    	  else if (dataCursor.getString(dataKind).equals(Integer.toString(Contacts.KIND_ORGANIZATION)))
	    	  {
	    		  if (dataTypeID == Contacts.ContactMethods.TYPE_CUSTOM)
	    			  dataTypeString = "Organization Custom";
	    		  else if (dataTypeID == Contacts.ContactMethods.TYPE_HOME)
	    			  dataTypeString = "Organization Home";
	    		  else if (dataTypeID == Contacts.ContactMethods.TYPE_OTHER)
	    			  dataTypeString = "Organization Other";
	    		  else if (dataTypeID == Contacts.ContactMethods.TYPE_WORK)
	    			  dataTypeString = "Organization Work";
	    		  if (IDtoContact.containsKey(ID))
	    			  IDtoContact.get(ID).addExtra(dataTypeString + ":" + dataCursor.getString(dataIndex));
	    		  else
	    		  {
	    			  Contact temp = new Contact(ID, dataCursor.getString(dataName), null, dataCursor.getString(dataIndex), null);
	    			  temp.addExtra(dataTypeString + ":" + dataCursor.getString(dataIndex));
	    			  IDtoContact.put(ID, temp);
	    		  }
	    	  }
	    	  else if (dataCursor.getString(dataKind).equals(Integer.toString(Contacts.KIND_POSTAL)))
	    	  {
	    		  if (dataTypeID == Contacts.ContactMethods.TYPE_CUSTOM)
	    			  dataTypeString = "Address Custom";
	    		  else if (dataTypeID == Contacts.ContactMethods.TYPE_HOME)
	    			  dataTypeString = "Address Home";
	    		  else if (dataTypeID == Contacts.ContactMethods.TYPE_OTHER)
	    			  dataTypeString = "Address Other";
	    		  else if (dataTypeID == Contacts.ContactMethods.TYPE_WORK)
	    			  dataTypeString = "Address Work";
	    		  if (IDtoContact.containsKey(ID))
	    			  IDtoContact.get(ID).addExtra(dataTypeString + ":" + dataCursor.getString(dataIndex));
	    		  else
	    		  {
	    			  Contact temp = new Contact(ID, dataCursor.getString(dataName), null, dataCursor.getString(dataIndex), null);
	    			  temp.addExtra(dataTypeString + ":" + dataCursor.getString(dataIndex));
	    			  IDtoContact.put(ID, temp);
	    		  }
	    	  }
	      }
	      while (dataCursor.moveToNext());
      }
      dataCursor.close();
      
      if (photoCursor.getCount() > 0)
      {
	      photoCursor.moveToFirst();
	      do
	      {
	    	  String ID = photoCursor.getString(photoPersonID);
	    	  if (IDtoContact.containsKey(ID))
	    		  IDtoContact.get(ID).setPicture(photoCursor.getBlob(photoIndex));
	    	  else 
	    		  IDtoContact.put(ID, new Contact(ID, null, null, null, photoCursor.getBlob(photoIndex))); //i sure hope this never happens...
	      }
	      while (photoCursor.moveToNext());
      }
      photoCursor.close();
      
      for (String ID: IDtoContact.keySet())
      {
    	  contacts.add(IDtoContact.get(ID));
      }
      
      Collections.sort(contacts); //sort by name
      
      adapter = new ContactAdapter(contacts); //set up the list
      resultList = (ListView)this.findViewById(R.id.ChooseResults);
      resultList.setAdapter(adapter);
      
      resultList.setOnItemClickListener(new OnItemClickListener()
      {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
			{
				//Log.d("Selected Position: ", Integer.toString(position));
				//selectedContact = resultList.getItemAtPosition(position).toString();
				//Log.d("Selected Contact:", selectedContact);
				Contact selected = (Contact)resultList.getItemAtPosition(position);
				if(has_file){
					String number = getOnlyNumerics(selected.getNumbers().get(0));
					WriteToFile(filepath, number);
					Log.d("Number being sent", getOnlyNumerics(number));
					
				}else{
					//wrap the person you choose into a file and recall this with that name
					ContactFileCreater writer = new ContactFileCreater(selected.getName(), selected.getNumbers(), selected.getDatas(), selected.getExtras(), selected.getPictureByte());
					writer.createFile();
					Intent i = new Intent(ContactChooser.this, ContactChooser.class);
					Bundle UserInfo = new Bundle();
					UserInfo.putString("Filepath", Environment.getExternalStorageDirectory().toString() + "/urbox/tmp/contact.ctc");
                    i.putExtras(UserInfo);
            		startActivity(i);
				}
				//Log.d("SelectedContact:",selected.toString() + selected.getExtras().toString());
				//String number = "1234";
				//Fire SMS sending sequence
						Intent next_intent = new Intent(ContactChooser.this, ContactSearch.class);
						Bundle destination_information = new Bundle();
						destination_information.putString("Filepath", Environment.getExternalStorageDirectory().toString() + "/urbox/tmp/contact.ctc");
						next_intent.putExtras(destination_information);	
						startActivityForResult(next_intent, 0x37);
				
				//String name = selected.getName();
				//be sure to sanitze input aka. deleted "-" from number
				//String number = getOnlyNumerics(number);
				//Log.d("Number Sent to", number);
				//Write pertinant info to a file

  				
				
			}
      });
      dataFilter = adapter.getFilter(); //set up the filter
      searchTerm = (EditText)this.findViewById(R.id.ChooseTerm);
      searchTerm.setOnKeyListener(new OnKeyListener()
      {
      	public boolean onKey(View v, int keyCode, KeyEvent event)
      	{
      		formatInput(keyCode); //makes phone numbers pretty
      		return false;
      	}
		});
  }
  
  @Override
  protected void onActivityResult( int requestCode, int resultCode,
  Intent data ){
	 finish();
  }
  
  public static String getOnlyNumerics(String str) {
	    
	    if (str == null) {
	        return null;
	    }

	    StringBuffer strBuff = new StringBuffer();
	    char c;
	    
	    for (int i = 0; i < str.length() ; i++) {
	        c = str.charAt(i);
	        
	        if (Character.isDigit(c)) {
	            strBuff.append(c);
	        }
	    }
	    return strBuff.toString();
	}
private void WriteToFile(String filepath, String number) {
		try{
			File root = Environment.getExternalStorageDirectory();
			if(root.canWrite()){
				Log.d("Writing to:", root.toString() + filepath);
				File dir = new File(root + "/urbox/tmp");
				File datafile = new File(dir, number + ".ubx");
				FileWriter datawriter = new FileWriter(datafile);
				BufferedWriter out = new BufferedWriter(datawriter);
				out.write(filepath);
				out.close();
			}
		}catch(IOException e){
			Log.e("Whoops", "Can't write" + e.getMessage());
		}
		
	}
	
  private void formatInput(int keyCode) //makes phone numbers match the format they are stored in android database
  {
  	String input = searchTerm.getText().toString();
  	String[] phoneNumberCheck = input.split("-");
  	
  	if (keyCode != KeyEvent.KEYCODE_DPAD_DOWN && keyCode != KeyEvent.KEYCODE_DPAD_UP && keyCode != KeyEvent.KEYCODE_DPAD_LEFT && keyCode != KeyEvent.KEYCODE_DPAD_RIGHT)
  	{
  		if (isPhoneNumber || keyCode == KeyEvent.KEYCODE_DEL)
  		{
	    		for (String column: phoneNumberCheck)
	    		{
	    			if (column != "")
	    			{
		    			try 
			    		{
			    			Integer.parseInt(column);
			    			isPhoneNumber = true;
			    		}
			    		catch (NumberFormatException e)
			    		{
			    			Log.d("Error:", column + " is not a phone number. Assuming name or email entry instead.");
			    			isPhoneNumber = false;
			    		}
	    			}
		    	}
  		}
	    	if (isPhoneNumber && keyCode != KeyEvent.KEYCODE_DEL)
	    	{
	    		if (input.length() == 1 && input.equals("1"))
	    			input = input + "-";
	    		else if (input.contains("-"))
	    		{
	    			if (input.indexOf("-") == 1)
	    			{
	    				if (input.length() == 5)
	    					input = input + "-";
	    				else if (input.length() == 9)
	    					input = input + "-";
	    			}
	    			else if (input.indexOf("-") == 3)
	    			{
	    				if (input.length() == 9)
	    					input = input.substring(0,7) + "-" + input.substring(7,9);
	    			}
	    		}
	    		else if (!input.contains("-") && input.length() == 3)
	    			input = input + "-";
	    	}
	    	searchTerm.setText(input); //update text box
	    	searchTerm.setSelection(input.length()); //move the cursor to the end again, otherwise they start typing at the beginning
	    	dataFilter.filter(input); //actually filter the data
  	}
  }
  
  private boolean checkInput() //makes sure the contents of the EditText is a phone number
  {
	  boolean response = true;
	  String input = searchTerm.getText().toString();
	  for (int i = 0; i < input.length(); i++)
	  {
		  if (!input.substring(i, i+1).equals("0") && !input.substring(i, i+1).equals("1") && !input.substring(i, i+1).equals("2") && !input.substring(i, i+1).equals("3") && !input.substring(i, i+1).equals("4") && !input.substring(i, i+1).equals("5") && !input.substring(i, i+1).equals("6") && !input.substring(i, i+1).equals("7") && !input.substring(i, i+1).equals("8") && !input.substring(i, i+1).equals("9") && !input.substring(i, i+1).equals("-"))
			  response = false;
	  }
	  Log.d("Input check results:", Boolean.toString(response));
	  return response;
  }
 
  private class ContactAdapter extends BaseAdapter implements ListAdapter
  {
	  private ContactFilter filter;
      private Context context;
      private final ArrayList<Contact> allContacts;
      private ArrayList<Contact> filteredContacts;
      

      public ContactAdapter(ArrayList<Contact> data)
      {
              context = ContactChooser.this;
              allContacts = data;
              filteredContacts = allContacts;
      }
      public View getView(int position, View convertView, ViewGroup parent) 
      {
    	  LinearLayout layout = new LinearLayout(context);
       	  ImageView picture = new ImageView(context);
          	  
       	  Bitmap image = filteredContacts.get(position).getPicture();
       	  if (image == null)
       	  {
         		  picture.setImageDrawable(getResources().getDrawable(R.drawable.contact));
       	  }
       	  else
     		  picture.setImageBitmap(image);
			           	  
       	  layout.setOrientation(LinearLayout.HORIZONTAL);
	   	  picture.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.FILL_PARENT));
	   	  layout.addView(picture);
			           	  
	   	  TextView information = new TextView(context);
	  	  information.setText(filteredContacts.get(position).toString());//" " + filteredContacts.get(position).getName() + " \n     " + filteredContacts.get(position).getNumbers() + " \n     " + filteredContacts.get(position).getEmails());
	   	  information.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.FILL_PARENT));
	   	  layout.addView(information);
	   	  return(layout);
      }
      public Filter getFilter()
      {
    	  if (filter == null)
    		  filter = new ContactFilter();
    	  return filter;
      }

      public int getCount()
      {
    	  return filteredContacts.size();
      }
      public Object getItem(int position)
      {
    	  return filteredContacts.get(position);
      }
      public long getItemId(int position) //i'm not really sure what this should be...
      {
    	  return 00000; //so i'll just throw out this for now, hopefully you don't actually need it
      }

  
  private class ContactFilter extends Filter
  {
	  @SuppressWarnings("unchecked")
	  @Override
	  protected FilterResults performFiltering(CharSequence term)
	  {
		  FilterResults results = new FilterResults();
		  String searchTerm = term.toString().toLowerCase();
		  
		  filteredContacts = (ArrayList<Contact>)allContacts.clone();
		  Log.d("Filter:", searchTerm);
		  //Log.d("FilteredContacts:", filteredContacts.toString());
		  if (searchTerm != null && searchTerm.length() > 0)
		  {
			  for (int index = filteredContacts.size() - 1; index >= 0; index --)
			  {
				  Contact temp = filteredContacts.get(index);
				  //Log.d("Temp Contact", temp.toString());
				  if (!temp.getName().toLowerCase().contains(searchTerm) && !temp.compareNumbers(searchTerm) && !temp.compareEmails(searchTerm))
					  filteredContacts.remove(index);
			  }
			  results.values = filteredContacts;
			  results.count = filteredContacts.size();
		  }
		  else
		  {
			  results.values = allContacts;
			  results.count = allContacts.size();
		  }
		  Log.d("Filter Results size:", Integer.toString(results.count));
		  //Log.d("Filter Results", results.values.toString());
		  return results;
		}
	  
	  @SuppressWarnings("unchecked")
	  @Override
	  protected void publishResults(CharSequence prefix, FilterResults results)
	  {
		  if (results.count > 0)
		  {
			  filteredContacts = (ArrayList<Contact>) results.values;
			  Collections.sort(filteredContacts); //sort by name
		  }
		  else if (checkInput())
		  {
			  ArrayList<Contact> temp = new ArrayList<Contact>();
			  Contact newContact = new Contact("", "Unknown Contact", searchTerm.getText().toString(), null, null);
			  temp.add(newContact);
			  filteredContacts = temp;
		  }
		  notifyDataSetChanged();
	  }
	}
  }
  private class Contact implements Comparable<Contact>
  {
	  private String name, id;
	  private ArrayList<String> numbers, datas; //i know the grammar is bad--- //assert(lol)
	  private Bitmap picture;
	  private ArrayList<String> extra;
	  private byte[] pictureByte;
	  public Contact()
	  {
		  name = "";
		  id = "";
		  numbers = new ArrayList<String>();
		  datas = new ArrayList<String>();
		  picture = null;
		  extra = new ArrayList<String>();
	  }
	  public Contact(String newID, String newName, String newNumber, String newData, byte[] newPicture)
	  {
		  numbers = new ArrayList<String>();
		  datas = new ArrayList<String>();
		  id = newID;
		  extra = new ArrayList<String>();
		  
		  if (newData != null)
			  datas.add(newData);
		  
		  if (newNumber != null)
			  numbers.add(newNumber);
		  
		  if (newName == null)
			  name = "Unnamed Contact";
		  else
			  name = newName;
		  
		  if (newPicture == null)
			  picture = null;
		  else
			  picture = BitmapFactory.decodeByteArray(newPicture, 0, newPicture.length);
	  }
	  public String getName()
	  {
		  return name;
	  }
	  public ArrayList<String> getNumbers()
	  {
		  return numbers;
	  }
	  public ArrayList<String> getDatas()
	  {
		  return datas;
	  }
	  public Bitmap getPicture()
	  {
		  return picture;
	  }
	  public void setName(String newName)
	  {
		  name = newName;
	  }
	  public void setNumbers(ArrayList<String> newNumbers)
	  {
		  numbers = newNumbers;
	  }
	  public void addNumber(String newNumber)
	  {
		  numbers.add(newNumber);
	  }
	  public void addData(String newData)
	  {
		  datas.add(newData);
	  }
	  public void setDatas(ArrayList<String> newDatas)
	  {
		  datas = newDatas;
	  }
	  public void setPicture(byte[] newPicture)
	  {
		  if (newPicture == null)
			  picture = null;
		  else
			  picture = BitmapFactory.decodeByteArray(newPicture, 0, newPicture.length);
		  pictureByte = newPicture;
	  }
	  public byte[] getPictureByte()
	  {
		  return pictureByte;
	  }
	  public void addExtra(String newExtra)
	  {
		  extra.add(newExtra);
	  }
	  public ArrayList<String> getExtras()
	  {
		  return extra;
	  }
	  public boolean compareNumbers(String term)
	  {
		  boolean response = false;
		  if (numbers != null)
		  {
			  for (String number: numbers)
			  {
				  if (number.contains(term))
				  {
					  response = true;
					  break;
				  }
			  }
		  }
		  return response;
	  }
	  public boolean compareEmails(String term)
	  {
		  boolean response = false;
		  if (datas != null)
		  {
			  for (String data: datas)
			  {
				  if (data.contains(term))
				  {
					  response = true;
					  break;
				  }
		  		}
		  }
		  return response;
	  }
	  public String toString()
	  {
		  String response = name + " \n";
		  for (String number: numbers)
			  response += number + " \n";
		  for (String data: datas)
			  response += data + " \n";
		  return response;
		  //return name + " \n     " + numbers.toString() + " \n     " + emails.toString();
	  }
	  public int compareTo(Contact other) //we sort by name here, i don't know why you would sort by anything else
	  {
		  return name.compareTo(other.getName());
	  }
	  public boolean equals(Contact other)
	  {
		  return name == other.getName() && numbers.containsAll(other.getNumbers()) && datas.containsAll(other.getDatas()) && picture == other.getPicture();
	  }
  }
}